package com.eflow.engine.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.eflow.engine.mapper.EflowActHisInstMapper;
import com.eflow.engine.mapper.EflowActRunInstMapper;
import com.eflow.model.e.BpmConst;
import com.eflow.model.e.CommentTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.impl.persistence.entity.ActivityInstanceEntity;
import org.flowable.engine.impl.runtime.ChangeActivityStateBuilderImpl;
import org.flowable.engine.runtime.ActivityInstance;
import org.flowable.engine.runtime.ChangeActivityStateBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @CLASSNAME BaseProcessService
 * @Description
 * @Auther JanHezz
 * @BLOG www.luckyhe.com
 * @DATE 2021/3/3 17:05
 */
@Slf4j
public abstract class AbstractEflowService implements BpmConst {
     @Autowired
    protected ManagementService managementService;
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected RuntimeService runtimeService;
    @Autowired
    protected RepositoryService repositoryService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected IdentityService identityService;
//    @Autowired
//    protected IFlowableCommentService flowableCommentService;
    @Autowired
    private EflowActRunInstMapper eflowActRunInstMapper;
    @Autowired
    private EflowActHisInstMapper
            eflowActHisInstMapper;

    /**
     * 添加审批意见
     *
     * @param taskId            任务id
     * @param userCode          处理人工号
     * @param processInstanceId 流程实例id
     * @param type              审批类型
     * @param message           审批意见
     */
    protected void addComment(String taskId, String userCode, String processInstanceId, CommentTypeEnum type, String message) {
        //1.添加备注
//        CommentVo commentVo = new CommentVo(taskId, userCode, processInstanceId, type, message);
//        flowableCommentService.addComment(commentVo);

    }

    /**
     * 添加审批意见
     *
     * @param userCode          处理人工号
     * @param processInstanceId 流程实例id
     * @param type              审批类型
     * @param message           审批意见
     */
    protected void addComment(String userCode, String processInstanceId, CommentTypeEnum type, String message) {
        this.addComment(null, userCode, processInstanceId, type, message);
    }

    /**
     * 删除跳转的历史节点信息
     *
     * @param disActivityId     跳转的节点id
     * @param processInstanceId 流程实例id
     */
    protected void deleteActivity(String disActivityId, String processInstanceId) {
        String tableName = managementService.getTableName(ActivityInstanceEntity.class);
        String sql = "select t.* from " + tableName + " t where t.PROC_INST_ID_=#{processInstanceId} and t.ACT_ID_ = #{disActivityId} " +
                " order by t.END_TIME_ ASC";
        List<ActivityInstance> disActivities = runtimeService.createNativeActivityInstanceQuery().sql(sql)
                .parameter("processInstanceId", processInstanceId)
                .parameter("disActivityId", disActivityId).list();
        //删除运行时和历史节点信息
        if (CollectionUtils.isNotEmpty(disActivities)) {
            ActivityInstance activityInstance = disActivities.get(0);
            sql = "select t.* from " + tableName + " t where t.PROC_INST_ID_=#{processInstanceId} and (t.END_TIME_ >= #{endTime} or t.END_TIME_ is null)";
            List<ActivityInstance> datas = runtimeService.createNativeActivityInstanceQuery().sql(sql).parameter("processInstanceId", processInstanceId)
                    .parameter("endTime", activityInstance.getEndTime()).list();
            List<String> runActivityIds = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(datas)) {
                datas.forEach(ai -> runActivityIds.add(ai.getId()));
                eflowActRunInstMapper.deleteRunActinstsByIds(runActivityIds);
                eflowActHisInstMapper.deleteActHisActInstByIds(runActivityIds);
            }
        }
    }

    /**
     * 执行跳转
     */
    protected void moveExecutionsToSingleActivityId(List<String> executionIds, String activityId) {
        moveExecutionsToSingleActivityId(executionIds,activityId,null);
    }

    /**
     * 执行跳转
     */
    protected void moveExecutionsToSingleActivityId(List<String> executionIds, String activityId, Map<String,Object> variables) {
       runtimeService.createChangeActivityStateBuilder()
                .moveExecutionsToSingleActivityId(executionIds, activityId)
                .processVariables(variables)
                .localVariable(activityId, VAR_REJECTED,true)
                .changeState();
    }

}
